package com.cdcas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Account {
    private String name;
    private int asset;

    public Account(String name,int asset) {
        this.name = name;
        this.asset = asset;
    }
    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void save(int asset) {
        this.readWriteLock.writeLock().lock();
        try {
            this.asset  += asset;
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName() +"修改资产，当前资产为：" + (this.asset/100.0));
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.readWriteLock.writeLock().unlock();
        }

    }

    @Override
    public String toString() {
        this.readWriteLock.readLock().lock();
        try {
            TimeUnit.SECONDS.sleep(100);
            return Thread.currentThread().getName() + "账户名称：" + this.name + "、账户余额：" + (this.asset/100.0);
        } catch (Exception e) {
            return null;
        } finally {
            this.readWriteLock.readLock().unlock();
        }

    }
}
